using System;
using System.Windows.Forms;
using System.IO;
using igp.net.DataModel;

namespace igp.net
{
    /// <summary>
    /// Represents the import window.
    /// </summary>
    public partial class FormImport : Form
    {
        /// <summary>
        /// Default constructor.
        /// </summary>
        public FormImport()
        {
            InitializeComponent();

            imageList1.Images.Add(Properties.Resources.add_pointset2);
            imageList1.Images.Add(Properties.Resources.add_polynomial);
            imageList1.Images.Add(Properties.Resources.add_function);
            imageList1.Images.Add(Properties.Resources.add_label);
            imageList1.Images.Add(Properties.Resources.add_integral);
            imageList1.Images.Add(Properties.Resources.add_labels);
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private string projectName;

        /// <summary>
        /// Shows the import window and interprets the input file.
        /// A list of available elements will be displayed.
        /// </summary>
        /// <param name="fileName"></param>
        public void Display(string fileName)
        {
            projectName = fileName;
            Text = string.Format("Import Project [ {0} ]", fileName);
            StreamReader sr = new StreamReader(fileName);
            string line;

            int a = -1;

            while ( (line = sr.ReadLine() ) != null)
            {
                if (line.StartsWith("<") && !line.StartsWith("</") && !line.StartsWith("<info>"))
                {
                    listViewAvailable.Items.Add(line);

                    int image = 5;

                    if (line.Contains("pointset"))
                    {
                        image = 0;
                    }

                    if (line.Contains("polynomial"))
                    {
                        image = 1;
                    }

                    if (line.Contains("function"))
                    {
                        image = 2;
                    }

                    if (line.Contains("label"))
                    {
                        image = 3;
                    }

                    if (line.Contains("integral"))
                    {
                        image = 4;
                    }

                    a++;
                    listViewAvailable.Items[a].ImageIndex = image;
                    string def = line;

                    while (!(line = sr.ReadLine()).StartsWith("</"))
                    {
                        if (line.StartsWith("ItemName"))
                        {
                            listViewAvailable.Items[a].Text += line.Substring(line.IndexOf("=")+1);
                        }
                        def = def + "\n\r" + line;
                    }
                    def = def + "\n\r" + line;
                    listViewAvailable.Items[a].ToolTipText = def;
                }
            }

            sr.Close();

            ShowDialog();
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            bool error = false;
            try
            {
                if (checkBoxClearProject.Checked) IgpProject.Singleton.clearProject();

                foreach (ListViewItem it in listViewAvailable.Items)
                {
                    if (it.Checked)
                    {
                        if (it.Text.StartsWith("<pointset>"))
                        {
                            igpPointSet ptset = IgpProject.Singleton.AddPointSet();
                            ptset.ReadData(new StringReader(it.ToolTipText));
                        }
                        if (it.Text.StartsWith("<function>"))
                        {
                            IgpFunction ptset = IgpProject.Singleton.AddFunction();
                            ptset.ReadData(new StringReader(it.ToolTipText));
                        }
                        if (it.Text.StartsWith("<polynomial>"))
                        {
                            igpPolynomial ptset = IgpProject.Singleton.AddPolynomial();
                            ptset.ReadData(new StringReader(it.ToolTipText));

                            foreach (IgpItem item in IgpProject.Singleton.Items)
                            {
                                if (item.TypeID == IgpItemType.Polynomial)
                                {
                                    igpPolynomial polynomial = ((igpPolynomial)item);

                                    if (polynomial.TrendlineName != "")
                                    {
                                        polynomial.TrendlinePoints = (igpPointSet) IgpProject.Singleton.GetItem(polynomial.TrendlineName);

                                        if (polynomial.TrendlinePoints == null)
                                        {
                                            error = true;
                                            FormMain.Singleton.LogMessage(string.Format("error: trendline points have not been selected for import. Imported trendline [ {0} ] is useless.", polynomial.ItemName));
                                        }

                                        polynomial.TrendlineName = "";
                                    }
                                }
                            }

                            IgpProject.Singleton.UpdatePolynomials();

                        }

                        if (it.Text.StartsWith("<label>"))
                        {
                            IgpLabel ptset = IgpProject.Singleton.AddLabel();
                            ptset.ReadData(new StringReader(it.ToolTipText));
                        }

                        if (it.Text.StartsWith("<integral>"))
                        {
                            igpIntegral ptset = IgpProject.Singleton.AddIntegral();
                            ptset.ReadData(new StringReader(it.ToolTipText));

                            foreach (IgpItem item in IgpProject.Singleton.Items)
                            {
                                if (item.TypeID == IgpItemType.Integral)
                                {
                                    igpIntegral integral = ((igpIntegral) item);

                                    if (integral.TopFunctionName != "")
                                    {
                                        integral.TopFunctionBase = (IgpFunctionBase)
                                                                   IgpProject.Singleton.GetItem(integral.TopFunctionName);

                                        if (integral.TopFunctionBase == null)
                                        {
                                            error = true;
                                            FormMain.Singleton.LogMessage(string.Format("error: integral top function has not been selected for import. Imported integral [ {0} ] will have the top function selected from existing ones.", integral.ItemName));
                                            integral.TopFunctionBase = IgpProject.Singleton.GetFunction(0);
                                        }

                                        integral.TopFunctionName = "";
                                    }

                                    if (integral.BottomFunctionName != "")
                                    {
                                        integral.BottomFunctionBase = (IgpFunctionBase) IgpProject.Singleton.GetItem(integral.BottomFunctionName);

                                        if (integral.BottomFunctionBase == null)
                                        {
                                            error = true;
                                            FormMain.Singleton.LogMessage(string.Format("error: integral bottom function has not been selected for import. Imported integral [ {0} ] will have the bottom function set to x axis.", integral.ItemName));
                                            integral.BottomFunctionBase = null;
                                        }

                                        integral.BottomFunctionName = "";
                                    }
                                }
                            }
                        }

                        if (it.Text.StartsWith("<View>"))
                        {
                            IgpProject.Singleton.View.ReadData(new StringReader(it.ToolTipText));
                        }

                        if (it.Text.StartsWith("<axes>"))
                        {
                            IgpProject.Singleton.View.Axes.ReadData(new StringReader(it.ToolTipText));
                        }

                        if (it.Text.StartsWith("<legend>"))
                        {
                            IgpProject.Singleton.View.Legend.ReadData(new StringReader(it.ToolTipText));
                        }
                    }
                }

                FormMain.Singleton.EditorWindow.SetActivePage(0);
                IgpProject.Singleton.UpdateResolutions();
                IgpProject.Singleton.View.UpdateDistances();

                FormMain.Singleton.EditorWindow.ReadViewProperities();
                FormMain.Singleton.PickerWindow.RefreshList();
                FormMain.Singleton.ClearView();
                FormMain.Singleton.Render();
                FormMain.Singleton.PaintView();
                
                if(!error)
                {
                    FormMain.Singleton.LogMessage(string.Format("Project [ {0} ] successfully imported", Path.GetFileName(projectName)));
                } else
                {
                    FormMain.Singleton.LogMessage(string.Format("Project [ {0} ] imported with errors. See log for details.", Path.GetFileName(projectName)));
                }
            }
            catch (Exception ex)
            {
                FormMain.Singleton.LogMessage(ex.Message);
            }
        }

        private void toolStripButtonSelectAll_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                it.Checked = true;
            }
        }

        private void toolStripButtonClear_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                it.Checked = false;
            }
        }

        private void toolStripMenuItemPtSet_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                if ( it.Text.Contains("pointset") ) 
                {
                    it.Checked = true;
                }
            }
        }

        private void toolStripMenuItemPolynomials_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                if (it.Text.Contains("polynomial"))
                {
                    it.Checked = true;
                }
            }
        }

        private void toolStripMenuItemFunctions_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                if (it.Text.Contains("function"))
                {
                    it.Checked = true;
                }
            }
        }

        private void toolStripMenuItemLabels_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                if (it.Text.Contains("label"))
                {
                    it.Checked = true;
                }
            }
        }

        private void toolStripMenuItemIntegrals_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem it in listViewAvailable.Items)
            {
                if (it.Text.Contains("integral"))
                {
                    it.Checked = true;
                }
            }
        }
    }
}